import {ChangeDetectorRef, Component, QueryList, ViewChild, ViewChildren} from "@angular/core";
import {AlertController, Content, IonicPage, NavController, NavParams, ToastController} from "ionic-angular";
import * as _ from 'lodash';

import {CollectionListProvider} from '../../../providers/collection/collection-list/collection-list.provider'
import {BASEURL} from "../../../config/url.config";
import {AdpLazyloadComponent} from "../../../components/common/adp-lazyload/adp-lazyload.component";
import {createChangeDetectorRef} from "@angular/core/src/view/refs";
import {LoadingService} from "../../../services/common/loading.service";
import {ThemeBrowserService} from "../../../services/native/theme-browser/theme-browser.service";
import {InformationDetailProvider} from "../../../providers/information/information-detail/information-detail.provider";
import {ToastService} from "../../../services/common/toast.service";

import {FileService} from "../../../services/native/file/file.service";
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";
import {File} from "@ionic-native/file";
import {FileTransfer} from "@ionic-native/file-transfer";
import {CacheImgService} from "../../../services/native/cache-img/cache-img.service";

@IonicPage()
@Component({
    selector: 'page-collection-list',
    templateUrl: 'collection-list.html',
    providers: [
        CollectionListProvider,
        ThemeBrowserService,
        InformationDetailProvider,
        ToastService,
        FileService,
        LocalStorageService,
        File,
        FileTransfer
    ]
})
export class CollectionListPage {
    @ViewChild(Content) content: Content;
    @ViewChildren(AdpLazyloadComponent) lazyImgs: QueryList<AdpLazyloadComponent>;
    // 消息列表
    private messageList: any[] = [];
    // 资讯列表
    private infoList: any[] = [];

    // 视口高度
    get itemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }

    // 内容是否滚动
    private isScrolling = false;
    // 提示框
    private alertObj: any;
    // 图片class
    private imgClassName = 'msl-card-img';
    // 图片列表
    private allImg: any;
    // 消息请求状态
    private msgRequestStatus: boolean = true;
    // 资讯请求状态
    private infoRequestStatus: boolean;
    // 收藏列表序号
    private listIndex: number;

    private azureInfo;

    constructor(private navCtrl: NavController,
                private navParams: NavParams,
                private collectionListProvider: CollectionListProvider,
                private ref: ChangeDetectorRef,
                private toastCtrl: ToastController,
                public alertCtrl: AlertController,
                private load: LoadingService,
                private themeBrowserService: ThemeBrowserService,
                private informationDetailProvider: InformationDetailProvider,
                private toastService: ToastService,
                private fileService: FileService,
                private cacheImg: CacheImgService
    ) {
    }

    public backButtonHandle = () => this.backClickHandle();

    ionViewDidEnter() {
        this.getAzureInfo(false);
        this.getMsgCollectList(true);
    }

    ionViewDidLoad() {
        this.listIndex = this.navParams.get('type');
    }

    // 返回
    backClickHandle() {
        this.navCtrl.pop();
    }

    getAzureInfo(flag) {
        this.fileService.getAzureInfo().subscribe((data) => {
            this.azureInfo = data.azureInfo;
            this.getInfoCollectList(flag)
        }, err => {
            console.log(err);
        });
    }


    // 获取资讯列表
    getInfoCollectList(flag) {
        flag ? this.load.showLoading() : null;
        this.collectionListProvider.getInfoCollectList().subscribe((res) => {
            flag ? this.load.dismissLoading() : null;
            if (res.length > 0) {
                this.infoList = res;
                this.getFullUrl();
            } else {
                this.infoList = [];
            }
            this.infoRequestStatus = true;
            if (this.infoList.length && this.content.scrollTop) {
                this.content.scrollToTop()
            }
        }, err => {
            this.infoRequestStatus = true;
            flag ? this.load.dismissLoading() : null;
            if (err.status == 500) {
                this.toastService.showToast('请求失败');
            }
        })
    }

    // 获取img完整路径
    getFullUrl() {
        for (let i in this.infoList) {
            if (this.infoList[i].listImageId) {
                //this.infoList[i].listImageId = BASEURL + '/azure/v1/download?resourceId=' + this.infoList[i].listImageId;
                this.cacheImg.getImgPath(this.infoList[i].listImageId, this.azureInfo)
                    .then((res) => {
                        this.infoList[i].listImageId = res;
                    })
                    .catch(() => {
                        this.infoList[i].listImageId = this.fileService.getCompletePath(this.infoList[i].listImageId, this.azureInfo);
                    });
            }
        }
    }

    // 删除资讯收藏
    deleteInfoCollect(e, id, sliding) {
        e.stopPropagation();
        e.preventDefault();
        this.showConfirm('确认删除?', () => {
            sliding.close();
            this.collectionListProvider.cancelCollect(id).subscribe((res) => {
                this.deleteData(this.infoList, 'contentId', id);
            }, err => {
                if (err.status == 500) {
                    this.toastService.showToast('删除失败');
                }
            })
        }, () => {
            sliding.close();
        })
    }

    // 获取消息列表
    getMsgCollectList(flag) {
        flag ? this.load.showLoading() : null;
        this.collectionListProvider.getMsgCollectList().subscribe((res) => {
            flag ? this.load.dismissLoading() : null;
            this.messageList = res;
            this.msgRequestStatus = true;
            if (this.messageList.length && this.content.scrollTop) {
                this.content.scrollToTop()
            }
        }, err => {
            flag ? this.load.dismissLoading() : null;
            this.msgRequestStatus = true;
            if (err.status == 500) {
                this.toastService.showToast('请求失败');
            }
        })
    }

    // 删除消息收藏
    deleteMsgCollect(e, id, sliding) {
        e.stopPropagation();
        e.preventDefault();
        this.showConfirm('确认删除?', () => {
            sliding.close();
            this.collectionListProvider.cancelCollectMsg(id).subscribe((res) => {
                this.deleteData(this.messageList, 'contentId', id);
            }, err => {
                if (err.status == 500) {
                    this.toastService.showToast('删除失败');
                }
            })
        }, () => {
            sliding.close();
        })
    }

    // 取消收藏数据删除
    private deleteData(data, field, id) {
        for (let f = 0; f < data.length; f++) {
            if (data[f][field] == id) {
                data.splice(f, 1);
            }
        }
    }

    // 收藏列表切换
    switchList(num) {
        this.listIndex = num;
        this.ref.detectChanges();
        this.ref.markForCheck();
        if (this.listIndex == 2) {
            this.getAzureInfo(true);
        } else {
            this.getMsgCollectList(true);
        }
    }

    // 跳转到资讯详情
    goToInfoDetail(id, name, url?: string) {
        if (url) {
            this.themeBrowserService.openBrowser(url, {
                name: name,
                id: id,
                status: true,
                callback1: (id) => this.collectInfo(id),
                callback2: (id) => this.cancelInfo(id)
            });
            return false
        }
        this.navCtrl.push('InformationDetailPage', {
            id: id,
            status: false
        });
    }

    // 收藏资讯
    collectInfo(id) {
        this.informationDetailProvider.collectInfo(id).subscribe(() => {
            this.themeBrowserService.setStatus(true);
            this.getInfoCollectList(false);
        }, error => {
            if (error.status == 500) {
                this.toastService.showToast('请求失败')
            }
        })
    }

    // 取消收藏
    cancelInfo(id) {
        this.informationDetailProvider.cancelCollect(id).subscribe(() => {
            this.themeBrowserService.setStatus(false);
            this.getInfoCollectList(false);
        }, error => {
            if (error.status == 500) {
                this.toastService.showToast('请求失败')
            }
        })
    }

    // 跳转到消息详情
    goToDetail(id) {
        this.navCtrl.push('MessageDetailPage', {
            id: id,
            status: false
        });
    }

    // 图片懒加载
    lazyLoad() {
        _.throttle(() => {
            this.lazyImgs['_results'].forEach((item) => {
                item.compute();
            });
        }, 50)();
    }

    /**
     * 确认框
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: '取消',
                handler: cancelCallback
            }, {
                text: '确定',
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }
}
